package org.shop.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.common.MyConstant;
import org.shop.entity.Merchant;
import org.shop.entity.Supplier;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.AttentionService;
import org.shop.service.MerchantService;
import org.shop.service.SupplierService;
import org.shop.service.UserService;
import org.shop.util.CommonUtil;
import org.shop.util.HttpClientUtil;
import org.shop.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {
	private static Logger logger = LogManager.getLogger(LoginController.class);

	@Autowired
	private MerchantService merchantService;
	@Autowired
	private UserService userService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private AttentionService attentionService;
	
	
	/**
	 * 登录s
	 * @param req
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("login")
	public String login(HttpServletRequest req,HttpServletResponse res) throws IOException{
		if (req.getHeader("x-requested-with") != null  
                && req.getHeader("x-requested-with").equalsIgnoreCase(  
                "XMLHttpRequest")) { // ajax 超时处理  
			res.setHeader("sessionstatus", "login");  
			res.setHeader("sessionstatus", "timeout");  
            Map<String, Object> error = new HashMap<String, Object>();  
            error.put("success", false);  
            error.put("sessionStatus", "timeout");  
            PrintWriter printWriter=res.getWriter();  
            printWriter.write(JsonUtils.toJson(error));  
            printWriter.flush();  
            printWriter.close();  
        }
		return "login";
	}
	
	/**
	 * 插入登录记录（商家和管理员）
	 * @param req
	 * @return
	 */
//	@RequestMapping("insertWebAndManagerLoginRecord")
//	public String insertWebAndManagerLoginRecord(HttpServletRequest req) {
//		Map<String,Object> paramMap = new HashMap<String,Object>();
//		DateUtils du = new DateUtils();
//		//获取登录人用户信息
//		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//		paramMap.put("userId", ud.getUserId());
//		paramMap.put("endTime", du.getLastYear());
//		loginRecordService.delLoginRecordOfYearByUserId(paramMap);
//		LoginRecord loginRecordInfo = new LoginRecord();
//		loginRecordInfo.setUserId(ud.getUserId());
//		loginRecordInfo.setLoginIp(getIpAddress(req));
//		try {
//			if(ud.getUserType() == MyConstant.USER_TYPE_SHOP) {
//				loginRecordInfo.setLoginRemark(ud.getUsername()+"商家登录");
//				loginRecordInfo.setLoginType((byte) 1);
//				loginRecordInfo.setLoginSrc((byte) 1);
//				loginRecordService.insertSelective(loginRecordInfo);
//			}else if(ud.getUserType() == MyConstant.USER_TYPE_ADMIN){
//				loginRecordInfo.setLoginRemark(ud.getUsername()+"管理员登录登录");
//				loginRecordInfo.setLoginType((byte) 2);
//				loginRecordInfo.setLoginSrc((byte) 1);
//				loginRecordService.insertSelective(loginRecordInfo);
//			}else {
//				req.setAttribute("contextPath", req.getContextPath());
//				loginRecordInfo.setLoginRemark(ud.getUsername()+"app登录");
//				loginRecordInfo.setLoginType((byte) 0);
//				loginRecordInfo.setLoginSrc((byte) 2);
//				loginRecordService.insertSelective(loginRecordInfo);
//			}
//		}catch(Exception e) {
//			e.printStackTrace();
//			logger.error(e.getMessage());
//		}
//		return "redirect:/index";
//	}
	
	
	
	/**
	 * 登录成功跳转
	 * @param req
	 * @return
	 */
//	@RequestMapping("app/appLogin")
//	@ResponseBody
//	public Map<String, Object> appLogin(@RequestBody UsersLoginVO usersLoginVO){
//		Map<String, Object> retMap=new HashMap<String, Object>();
//		FTPClient ftpClient =null;
//		try{
//			logger.trace("接收参数"+JsonUtils.toJson(usersLoginVO));
//			if(StringUtils.isEmpty(usersLoginVO.getUserId())){
//				retMap.put("state", 0);
//				retMap.put("msg", "参数正确，用户唯一标识不能为空");
//				return retMap;
//			}
//			if(StringUtils.isEmpty(usersLoginVO.getUserName())){
//				retMap.put("state", 0);
//				retMap.put("msg", "参数正确，用户登录名不能为空");
//				return retMap;
//			}
//			if(StringUtils.isEmpty(usersLoginVO.getStudentNo())){
//				retMap.put("state", 0);
//				retMap.put("msg", "参数正确，学号不能为空");
//				return retMap;
//			}
//			if(StringUtils.isEmpty(usersLoginVO.getName())){
//				retMap.put("state", 0);
//				retMap.put("msg", "参数正确，姓名不能为空");
//				return retMap;
//			}
//			if(StringUtils.isEmpty(usersLoginVO.getNickname())){
//				retMap.put("state", 0);
//				retMap.put("msg", "参数正确，昵称不能为空");
//				return retMap;
//			}
//			if(StringUtils.isEmpty(usersLoginVO.getPhone())){
//				retMap.put("state", 0);
//				retMap.put("msg", "参数正确，联系电话不能为空");
//				return retMap;
//			}
//			if(StringUtils.isEmpty(usersLoginVO.getCertNo())){
//				retMap.put("state", 0);
//				retMap.put("msg", "参数正确，证件号码不能为空");
//				return retMap;
//			}
//			if(StringUtils.isEmpty(usersLoginVO.getSex())){
//				retMap.put("state", 0);
//				retMap.put("msg", "参数正确，性别不能为空");
//				return retMap;
//			}
//			if(StringUtils.isEmpty(usersLoginVO.getSchoolId())){
//				retMap.put("state", 0);
//				retMap.put("msg", "参数正确，学校标识不能为空");
//				return retMap;
//			}
//			if(StringUtils.isEmpty(usersLoginVO.getSchoolName())){
//				retMap.put("state", 0);
//				retMap.put("msg", "参数正确，学校名称不能为空");
//				return retMap;
//			}
//			if(StringUtils.isEmpty(usersLoginVO.getPic())){
//				retMap.put("state", 0);
//				retMap.put("msg", "参数正确，头像不能为空");
//				return retMap;
//			}
//			Users users =userService.findUserByStudentCode(usersLoginVO.getUserId());
//			if(users==null){
//				users=new Users();
//				users.setStudentCode(usersLoginVO.getUserId());
//				users.setUserType(0l);
//				users.setLoginName(usersLoginVO.getUserName());
//				users.setStudentNo(usersLoginVO.getStudentNo());
//				users.setRealName(usersLoginVO.getName());
//				users.setUserName(usersLoginVO.getNickname());
//				users.setPhone(usersLoginVO.getPhone());
//				users.setIdNo(usersLoginVO.getCertNo());
//				if("1".equals(usersLoginVO.getSex())){
//					users.setUserSex("男");
//				}else if("2".equals(usersLoginVO.getSex())){
//					users.setUserSex("女");
//				}else{
//					retMap.put("state", 0);
//					retMap.put("msg", "参数正确，性别参数不正确");
//					return retMap;
//				}
//				if(StringUtils.isEmpty(usersLoginVO.getCountry())){
//					users.setCountry("中国");
//				}else{
//					users.setIdNo("外国");
//				}
//				users.setNation(usersLoginVO.getNation());
//				School school=schoolService.getSchoolBySchoolCode(usersLoginVO.getSchoolId());
//				if(school==null){
//					school=new School();
//					school.setSchoolCode(usersLoginVO.getSchoolId());
//					school.setSchoolName(usersLoginVO.getSchoolName());
//					school.setCreateDate(new Date());
//					school.setState((byte)1);
//					schoolService.insertSelective(school);
//				}else{
//					school.setSchoolName(usersLoginVO.getSchoolName());
//					schoolService.updateByPrimaryKeySelective(school);
//				}
//				users.setSchoolId(school.getSchoolId());
//				String ftp_photoDirectory="shop/tx/" + DateUtils.toYmdX(new Date());
//				byte[] picArr=Base64Utils.decode(usersLoginVO.getPic().getBytes());
//				ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
//				String myFileName=FtpUtil2.generateFileName("temp.jpg");
//				try(InputStream is=new ByteArrayInputStream(picArr)){
//					FtpUtil2.upload(myFileName, is, ftpClient);
//					users.setUserPhoto(ftp_photoDirectory+"/"+myFileName);
//				}catch (Exception e) {
//					e.printStackTrace();
//				}
//				userService.insertSelective(users);
//			}else{
//				users.setStudentCode(usersLoginVO.getUserId());
//				users.setUserType(0l);
//				users.setLoginName(usersLoginVO.getUserName());
//				users.setStudentNo(usersLoginVO.getStudentNo());
//				users.setRealName(usersLoginVO.getName());
//				users.setUserName(usersLoginVO.getNickname());
//				users.setPhone(usersLoginVO.getPhone());
//				users.setIdNo(usersLoginVO.getCertNo());
//				if("1".equals(usersLoginVO.getSex())){
//					users.setUserSex("男");
//				}else if("2".equals(usersLoginVO.getSex())){
//					users.setUserSex("女");
//				}else{
//					retMap.put("state", 0);
//					retMap.put("msg", "参数正确，性别参数不正确");
//					return retMap;
//				}
//				if(StringUtils.isEmpty(usersLoginVO.getCountry())){
//					users.setCountry("中国");
//				}else{
//					users.setIdNo("外国");
//				}
//				users.setNation(usersLoginVO.getNation());
//				School school=schoolService.getSchoolBySchoolCode(usersLoginVO.getSchoolId());
//				if(school==null){
//					school=new School();
//					school.setSchoolCode(usersLoginVO.getSchoolId());
//					school.setSchoolName(usersLoginVO.getSchoolName());
//					school.setCreateDate(new Date());
//					school.setState((byte)1);
//					schoolService.insertSelective(school);
//				}else{
//					school.setSchoolName(usersLoginVO.getSchoolName());
//					schoolService.updateByPrimaryKeySelective(school);
//				}
//				users.setSchoolId(school.getSchoolId());
//				String ftp_photoDirectory="shop/tx/" + DateUtils.toYmdX(new Date());
//				byte[] picArr=Base64Utils.decode(usersLoginVO.getPic().getBytes());
//				ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
//				String myFileName=FtpUtil2.generateFileName("temp.jpg");
//				try(InputStream is=new ByteArrayInputStream(picArr)){
//					FtpUtil2.upload(myFileName, is, ftpClient);
//					users.setUserPhoto(ftp_photoDirectory+"/"+myFileName);
//				}catch (Exception e) {
//					e.printStackTrace();
//				}
//				userService.updateByPrimaryKeySelective(users);
//			}
//			retMap.put("state", 1);
//			retMap.put("msg", "操作成功");
//		}catch(Exception e){
//			logger.error(e);
//			retMap.put("state", 0);
//			retMap.put("msg", "操作失败");
//		}
//		return retMap;
//	}
	/**
	 * 登录成功跳转(web,manager,供应商,自营，生活管理员)
	 * @param req
	 * @return
	 */
	@RequestMapping("index")
	public String index(HttpServletRequest req, Model model){
		Map<String,Object> paramMap = new HashMap<String,Object>();
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		model.addAttribute("user", ud);
		paramMap.put("targetId", ud.getMerchantId());
		paramMap.put("attentionType", 1);
		int fansCount = attentionService.getMyFocusAndFansCount(paramMap);
		model.addAttribute("fansCount",fansCount);
		if(ud.getUserType() == MyConstant.USER_TYPE_SHOP || ud.getUserType() == MyConstant.USER_TYPE_STUDENTSHOP) {
			if(ud.getMerchantId()==null){
				return "web/applyMerchant";
			}else{
				Merchant merchant=merchantService.selectByPrimaryKey(ud.getMerchantId());
				if(merchant.getState()==1){
					return "web/waitApplyMerchant";
				}else if(merchant.getState()==3){
					return "web/reapplyMerchant";
				}else if(merchant.getState()==0){
					return "web/closeMerchant";
				}
			}
			return "web/index";
		}else if(ud.getUserType() == MyConstant.USER_TYPE_ADMIN){
			return "manager/index";
		}else if(ud.getUserType() == MyConstant.USER_TYPE_SUPPLIER){
			Supplier supplier=supplierService.findSupplierByUserId(ud.getUserId());
			if(supplier==null){
				return "supplier/addSupplier";
			}
			return "supplier/index";
		}else if(ud.getUserType() == MyConstant.USER_TYPE_AUTOTROPHY){
			return "autotrophy/index";
		}else if(ud.getUserType() == MyConstant.USER_TYPE_LIVEMANAGER) {
			return "liveManager/index";
		}else if(ud.getUserType() == MyConstant.USER_TYPE_BBSMANAGER) {
			return "bbsManager/index";
		}
		return "app/index";
	}
	/**
	 * 获取验证码
	 * @param req
	 * @return
	 */
	@RequestMapping("getVolatileCode")
	@ResponseBody
	public Map<String, Object> getVolatileCode(HttpServletRequest req, Model model){
		Map<String, Object> retMap=new HashMap<String, Object>();
		try{
			String phone=req.getParameter("phone");
			int random=(int)((Math.random()*9+1)*1000);
			HttpSession session=req.getSession(false);
			session.setAttribute(phone, random);
			String smsUrl=CommonUtil.getPropertiesParam("smsUrl");
			String account=CommonUtil.getPropertiesParam("account");
			String password=CommonUtil.getPropertiesParam("password");
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("account", account);
			map.put("password", password);
			map.put("phone", phone);
			map.put("msg", "验证码："+random);
			String bodyJson=HttpClientUtil.doPostJson(smsUrl, JsonUtils.toJson(map));
			String code=JsonUtils.fromJson(bodyJson).get("code").asText();
			if(code.equals("0")){
				retMap.put("state", 1);
				retMap.put("msg", "操作成功");
			}else{
				retMap.put("state", 0);
				retMap.put("msg", "操作失败");
			}
		}catch(Exception e){
			e.printStackTrace();
			retMap.put("state", 0);
			retMap.put("msg", "操作失败");
		}
		return retMap;
	}
	
	
	
	 /** 
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址, 
*  
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？ 
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。 
     *  
     * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130, 
     * 192.168.1.100 
     *  
     * 用户真实IP为： 192.168.1.110 
     *  
     * @param request 
     * @return 
     */  
    public static String getIpAddress(HttpServletRequest request) {  
    	String ip = request.getHeader("x-forwarded-for");  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }  
        return ip;  
    } 
	
}
